//
//  YPRegistViewController.m
//  ChengHuiTong
//
//  Created by KiVen on 15/11/12.
//  Copyright © 2015年 张文权. All rights reserved.
//

#import "YPRegistViewController.h"
#import "YPPerfectInformationViewController.h"
#import "YPGetCodeModel.h"
#import "YPRegistOneTableViewCell.h"
#import "SelectView.h"

#import "LewPopupViewAnimationSlide.h"

#import "LewPopupViewAnimationDrop.h"

#import "LewPopupViewController.h"
#import "DQAlertView.h"
#import "MainTabbarViewController.h"

@interface YPRegistViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    
    /**
     *  时间变量
     */
    int _remainingTime;
    /**
     *  倒计时label
     */
    UIButton *_countDownButton;
    
    /**
     *  获取验证码
     *
     *  @return <#return value description#>
     */
    
    UITextField * _getCodeTextField;

    TPKeyboardAvoidingTableView * _registTableView;
    
    //    自定义的alertview
    DQAlertView * _customAlertView;

}
@property(nonatomic,strong)NSArray *dataSource;

@end

@implementation YPRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"注册";
    
    _remainingTime      = 60;

    [self creatRegistView];

}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    [MobClick beginLogPageView:@"注册"];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:YES];
    
    [MobClick endLogPageView:@"注册"];
}
- (void)creatRegistView{
    
    _registTableView = [[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 15, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _registTableView.dataSource = self;
    _registTableView.delegate = self;
    _registTableView.scrollEnabled = NO;
    //    没有数据的时候  去掉单元格的细线
    _registTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    UIView * tableFootView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    tableFootView.backgroundColor =  UIColorFromRGB(0xf5f5f5);
    
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"注册即表示同意《诚汇通协议书》"];
    NSRange strRange = {7,([str length]-7)};
    [str addAttribute:NSForegroundColorAttributeName value:UIColorFromRGB(0x0b7bf8)range:strRange];
    UIButton * contentButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, 20)];
    contentButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [contentButton addTarget:self action:@selector(AgreeUserProtocolClick) forControlEvents:UIControlEventTouchUpInside];
    contentButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [contentButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [contentButton setAttributedTitle:str forState:UIControlStateNormal];
    
    [tableFootView addSubview:contentButton];

    
    UIButton*registButton=[[UIButton alloc] initWithFrame:CGRectMake(10, 50, SCREEN_WIDTH-20, 40)];
    [registButton setTitle:@"注册" forState:0];
    [registButton setBackgroundColor:kColor_AppNavColor];
    registButton.layer.cornerRadius=5;
    registButton.titleLabel.font=[UIFont boldSystemFontOfSize:18];
    registButton.clipsToBounds=YES;
    [registButton addTarget:self action:@selector(registButtonClcik) forControlEvents:UIControlEventTouchUpInside];
    [tableFootView addSubview:registButton];

    _registTableView.tableFooterView=tableFootView;

    [self.view addSubview:_registTableView];
    
    
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:2 inSection:0];
    YPRegistOneTableViewCell * cell2 = [_registTableView cellForRowAtIndexPath:indexPath2];
    [cell2.getCodeButton setTitle:@"获取验证码"forState:UIControlStateNormal];
    [cell2.getCodeButton addTarget:self action:@selector(requestVerificationCodeAction) forControlEvents:UIControlEventTouchUpInside];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;{
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row ==2) {
        
        
        YPRegistOneTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell0"];
        if (!cell) {
            cell = [[YPRegistOneTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell0"];
            
            cell.contentTextField.keyboardType = UIKeyboardTypeNumberPad;
            UILabel *subLabel = [UILabel creatWithFrame:CGRectMake(0, 5, SCREEN_WIDTH, 15)
                                                   font:[UIFont systemFontOfSize:12]
                                                   text:@"*注册手机号必须与银行卡预留手机号一致*"
                                              textColor:kColor_redNumberColor
                                          textAlignment:1];
            [cell.contentView addSubview:subLabel];
            
            cell.titleLabel.top = subLabel.bottom;
            cell.contentTextField.top = cell.titleLabel.top;
            cell.getCodeButton.top = cell.titleLabel.top + 5;

        }
        cell.titleLabel.text = [_dataSource[indexPath.row]objectForKey:@"title"];
        return cell;

        
    }else{
        
        
        YPRegistOneTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        if (!cell) {
            cell = [[YPRegistOneTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell1"];
            
            
            if (indexPath.row ==0) {
                
                cell.contentTextField.placeholder = @"2-20位数字、字母或中文";
                
            }else if (indexPath.row ==1){
                
                cell.contentTextField.placeholder = @"只支持国内11位手机号";
                cell.contentTextField.keyboardType = UIKeyboardTypeNumberPad;
                cell.contentTextField.delegate =self;
                
                
            }else if (indexPath.row==3){
                
                cell.contentTextField.placeholder = @"8-20位字母或数字";
                cell.contentTextField.secureTextEntry = YES;
                cell.contentTextField.delegate =self;


            }

        }
        cell.titleLabel.text = [_dataSource[indexPath.row]objectForKey:@"title"];
        

        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 2) {
        
        return 60;
        
    }else{
        
        return 44;
    }
    
}
//获取验证码
- (void)requestVerificationCodeAction{
    
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0];
    
    NSIndexPath *indexPath0 = [NSIndexPath indexPathForRow:0 inSection:0];

    YPRegistOneTableViewCell * cell0 = [_registTableView cellForRowAtIndexPath:indexPath0];

    
    YPRegistOneTableViewCell * cell1 = [_registTableView cellForRowAtIndexPath:indexPath1];

    NSLog(@"phoneTextField=%@",cell1.contentTextField.text);
    if (cell0.contentTextField.text.length < 1) {
        
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入用户名"];
        return;
        
    }
    
    if (cell1.contentTextField.text.length < 1) {
        
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入手机号码"];
        return;

    }
    
    if ([LGToolMethods validateMobile:cell1.contentTextField.text] == NO) {
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"您输入的号码不正确,请重新输入"];
        return;
    }
    _remainingTime      = 60;
    
    
    YPGetCodeBin * bin = [[YPGetCodeBin alloc]init];
    bin.phone = cell1.contentTextField.text;
    
    [YPHttpRequestMethod sendAsyRequestURL:CMD_GET_CODE withData:[bin dictionaryValue] withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        if ([responseDictionary[@"status"] intValue]== 0) {
        
            [self buttonCountdown];

            YPGetCodeModel * model = [[YPGetCodeModel alloc]initWithDictionary:responseDictionary];
            self.getCodeModel = model;
        
        }else if ([responseDictionary[@"status"] intValue]== 1005){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"无效手机号"];
            return;

        }else if ([responseDictionary[@"status"] intValue]== 1006){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"手机号已经存在"];
            return;

        }else if ([responseDictionary[@"status"] intValue]== 1309){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"发送短信失败"];
            return;

        }
        
        
    } withFailedBlock:^(NSError *error) {
        
        
    } withIndicator:YES atView:self.view];

    
}
-(void)buttonCountdown{
    
    
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:2 inSection:0];
    YPRegistOneTableViewCell * cell2 = [_registTableView cellForRowAtIndexPath:indexPath2];
    
    
    if (_remainingTime > 0) {
        [self performSelector:@selector(buttonCountdown) withObject:nil afterDelay:1.0];
        _remainingTime--;
        [cell2.getCodeButton setTitle:[NSString stringWithFormat:@"%d秒",_remainingTime] forState:UIControlStateNormal];
        cell2.getCodeButton .userInteractionEnabled = NO;
        [cell2.getCodeButton setTitleColor:UIColorFromRGB(0xe4e3e2) forState:UIControlStateNormal];

        if (_remainingTime == 0) {
            
            [cell2.getCodeButton  setTitle:@"获取验证码" forState:UIControlStateNormal];
            cell2.getCodeButton .userInteractionEnabled = YES;
            [cell2.getCodeButton setTitleColor:kColor_AppNavColor forState:UIControlStateNormal];

        }
        
    }
    else{
        _remainingTime      = 60;
    }
    
}


//注册按钮事件
- (void)registButtonClcik{

    //    获得用户名
    NSIndexPath *indexPath0 = [NSIndexPath indexPathForRow:0 inSection:0];
    YPRegistOneTableViewCell * cell0 = [_registTableView cellForRowAtIndexPath:indexPath0];
//    获得手机号
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0];
    YPRegistOneTableViewCell * cell1 = [_registTableView cellForRowAtIndexPath:indexPath1];
//    获取验证码
    NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:2 inSection:0];
    YPRegistOneTableViewCell * cell2 = [_registTableView cellForRowAtIndexPath:indexPath2];
//    获取登录密码
    NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:3 inSection:0];
    YPRegistOneTableViewCell * cell3 = [_registTableView cellForRowAtIndexPath:indexPath3];


    if (cell0.contentTextField.text.length <1) {
        
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入用户名"];
        return;
        
    }else if (cell1.contentTextField.text.length <1){
        
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入手机号"];
        return;

    }
    else if (cell2.contentTextField.text.length <1){
        
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入验证码"];
        return;

        
    }else if (cell3.contentTextField.text.length <1){
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入登录密码"];
        return;
        
    }

    
//    YPRegistBin * bin = [[YPRegistBin alloc]init];
//    
//    bin.encrypt=@"1";
//    bin.username =[GetCodeString getCodeWithString:cell0.contentTextField.text];
//    bin.phone =cell1.contentTextField.text;
//    bin.password =[GetCodeString getCodeWithString:cell3.contentTextField.text];
//    bin.code = cell2.contentTextField.text;
//    bin.smsid = self.getCodeModel.smsid;
//    bin.app_type = @"1";
//    
//    
//    [YPShareAccountInfo shareAccountInfo].phone = cell1.contentTextField.text;
    
    
    NSLog(@"用户名---%@",[GetCodeString getCodeWithString:cell0.contentTextField.text]);
    
    [RequestModel RegisterSuccessWithname:[GetCodeString getCodeWithString:cell0.contentTextField.text] andPwd:[GetCodeString getCodeWithString:cell3.contentTextField.text] phone:[GetCodeString getCodeWithString:cell1.contentTextField.text] code:cell2.contentTextField.text smsid:self.getCodeModel.smsid Block:^(id responseDictionary) {
        
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        NSLog(@"responseDictionary:%@",responseDictionary);
        
        YPShareAccountInfo*userinfo=[YPShareAccountInfo shareAccountInfo];
        userinfo.userName =cell0.contentTextField.text;
        userinfo.phone =cell1.contentTextField.text;
        [userinfo saveData];
        
        if ([responseDictionary[@"status"] intValue]== 0) {
            
            YPShareAccountInfo*userinfo=[YPShareAccountInfo shareAccountInfo];
            
            [userinfo setDataWithDic:responseDictionary];
            userinfo.userName =cell0.contentTextField.text;
            [userinfo saveData];
            [self sendDevice_token];
            
            [self.navigationController dismissViewControllerAnimated:YES completion:^{
                
                [self creatRegistSuccessView];
                
                
            }];
            
            if (self.completBlock) {
                self.completBlock(TOKEN);
            }
            
        }else if ([responseDictionary[@"status"] intValue]== 1002){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"用户名小于2位"];
            
        }else if ([responseDictionary[@"status"] intValue]== 1003){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"用户名大于20位"];
            
        }else if ([responseDictionary[@"status"] intValue]== 1004){
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"用户名已存在"];
            
            
        }else if ([responseDictionary[@"status"] intValue]== 1005){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"无效的手机号"];
            
        }else if ([responseDictionary[@"status"] intValue]== 1006){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"该手机号已经注册"];
            
        }
        else if ([responseDictionary[@"status"] intValue]== 1007){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"密码小于8位"];
            
        }
        else if ([responseDictionary[@"status"] intValue]== 1008){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"密码大于20位"];
            
        }
        else if ([responseDictionary[@"status"] intValue]== 1010){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"验证码已经失效"];
            
        }
        else if ([responseDictionary[@"status"] intValue]== 1011){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"验证码不正确"];
            
        }
        else if ([responseDictionary[@"status"] intValue]== 9000){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"系统繁忙,请稍后重试"];
            
        }
        
        
    } failBlock:^(id obj) {
        
        [MBProgressHUD showError:@"网络连接失败" toView:self.view];
        
    }];

    
}
- (void)sendDevice_token{
    
    
    YPDeviceBin * bin = [[YPDeviceBin alloc]init];
    bin.token = [YPShareAccountInfo shareAccountInfo].token;
    bin.device_token = [LGToolMethods getUserDefaultsObjForKey:@"deviceKey"];
    
    NSLog(@"%@",[LGToolMethods getUserDefaultsObjForKey:@"deviceKey"]);
    
    [YPHttpRequestMethod sendAsyRequestURL:CMD_SEND_DEVICE_TOKEN withData:[bin dictionaryValue] withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        NSLog(@"responseDictionary=%@",responseDictionary);
        
        
    } withFailedBlock:^(NSError *error) {
        
        
    } withIndicator:NO atView:self.view];
    
    
    
    
}

- (void)creatRegistSuccessView{
    
    _customAlertView = [[DQAlertView alloc] initWithTitle:nil message:nil cancelButtonTitle:nil otherButtonTitle:nil];
    _customAlertView.customFrame = CGRectMake(30, 200, SCREEN_WIDTH-(2*30), 160);
    _customAlertView.shouldDismissOnOutsideTapped = YES;
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-(2*30), 160)];
    contentView.backgroundColor = [UIColor whiteColor];
    
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-(2*30), 40)];
    
    titleLabel.backgroundColor = kColor_AppNavColor;
    
    titleLabel.text = @"注册成功";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [contentView addSubview:titleLabel];
    
    NSArray *titleArray = @[@"马上开通银行存管",@"以后再说"];
    
    for (int i= 0; i<2; i++) {
        
        UIButton * laterButton = [UIButton buttonWithType:UIButtonTypeCustom];
        laterButton.frame = CGRectMake(0,40+i*60.5, SCREEN_WIDTH-(2*30), 60);
//        laterButton.backgroundColor = [UIColor cyanColor];
        laterButton.tag = i+100;
        [laterButton setTitle:titleArray[i] forState:UIControlStateNormal];
        laterButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
        laterButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15,0, 15);//设置title在button上的位置（上top，左left，下bottom，右right）
        [laterButton addTarget:self action:@selector(laterButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:laterButton];
        
        UIImageView * enterImageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-(2*30)-20-20,(60-31)/2, 17, 30)];
        enterImageView.image = [UIImage imageNamed:@"enter"];
        [laterButton addSubview:enterImageView];
        
        if (i ==1) {
            
            UILabel * lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 40+i*59.5, SCREEN_WIDTH-(2*30)-20, .5)];
            lineLabel.backgroundColor = [UIColor grayColor];
            [contentView addSubview:lineLabel];
            [laterButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }else{
            
            [laterButton setTitleColor:kColor_AppNavColor forState:UIControlStateNormal];

        }
        
    }
    
    
    
    _customAlertView.contentView = contentView;
    
    
    [_customAlertView show];
    

    
}
- (void)laterButtonClick:(UIButton *)sender{
    
    
    
    if (sender.tag ==100) {
        
        [_customAlertView dismiss];

        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        MainTabbarViewController * mainTabbar =(MainTabbarViewController *) window.rootViewController;
        
        YPGoWebView(String_Connect(CMD_DEPOSITORY, @"&token=", TOKEN), mainTabbar.viewControllers[mainTabbar.selectedIndex]);
        
        
    }else{
        
        [_customAlertView dismiss];

        [self dismissViewControllerAnimated:YES completion:^{
            

        }];
        
    }
    
}
- (void)AgreeUserProtocolClick{
    
    NSString * url = [NSString stringWithFormat:@"%@index.php?m=app&c=app&a=regProtocol",kAppHostAddress];
    YPWebViewController * webVC = [[YPWebViewController alloc]initWithUrl:url];
    webVC.title = @"注册协议";
    [self.navigationController pushViewController:webVC animated:YES];

}

-(NSArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = @[@{@"title":@"用户名"},
                        @{@"title":@"手机号"},
                        @{@"title":@"验证码"},
                        @{@"title":@"登录密码"}];
        
    }
    
    return _dataSource;
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;  {
    
    //    获得手机号
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0];
    YPRegistOneTableViewCell * cell1 = [_registTableView cellForRowAtIndexPath:indexPath1];
    
    //    获取登录密码
    NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:3 inSection:0];
    YPRegistOneTableViewCell * cell3 = [_registTableView cellForRowAtIndexPath:indexPath3];


    if (textField == cell1.contentTextField) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }else if (textField ==cell3.contentTextField){
        
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 20) {
            return NO;
        }

    }
    
    return YES;
}
- (void)textFieldDidChange:(UITextField *)textField
{
    
    //    获得手机号
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0];
    YPRegistOneTableViewCell * cell1 = [_registTableView cellForRowAtIndexPath:indexPath1];
    
    //    获取登录密码
    NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:3 inSection:0];
    YPRegistOneTableViewCell * cell3 = [_registTableView cellForRowAtIndexPath:indexPath3];


    if (textField == cell1.contentTextField) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }else if (textField ==cell3.contentTextField){
    
        if (textField.text.length > 20) {
            textField.text = [textField.text substringToIndex:20];
        }

    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
